<template>
  <!-- 台账 -->
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        ref="search"
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
        :spoNum="2"
        @change="change"
      >
        <div class="ccui-tab-wrapper">
          <el-button
            :type="isFocus === 1 ? 'table-top-active' : 'table-top'"
            size="mini"
            >全部 ({{ totalNum }})</el-button
          >
        </div>
        <div class="ccui-extend-btn">
          <el-export-button
            class="export-button"
            @export-excel="exportExcel"
            @export-pdf="exportPdf"
          ></el-export-button>
        </div>

        <template slot="search">
          <el-input
            v-model="formData.exwarehouseName"
            clearable
            searchLabel="出库单名称"
            placeholder="请输入出库单名称查询"
            @blur="handleTrim('exwarehouseName')"
          ></el-input>
          <el-input
            v-model="formData.exwarehouseCode"
            clearable
            searchLabel="出库单编号"
            placeholder="请输入出库单编号查询"
            @blur="handleTrim('exwarehouseCode')"
          ></el-input>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位查询"
            @blur="handleTrim('reportInOrgName')"
          ></el-input>
          <el-input
            v-model="formData.warehouseName"
            clearable
            searchLabel="仓库"
            placeholder="请输入仓库查询"
            @blur="handleTrim('warehouseName')"
          ></el-input>
          <el-date-picker
            v-model="formData.paymentApplyDate"
            searchLabel="编制日期"
            clearable
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.exwarehouseName"
          clearable
          searchLabel="出库单名称"
          placeholder="请输入出库单名称查询"
          slot="searchItem2"
          @blur="handleTrim('exwarehouseName')"
        ></el-input>
        <el-input
          v-model="formData.exwarehouseCode"
          clearable
          searchLabel="出库单编号"
          placeholder="请输入出库单编号查询"
          slot="searchItem3"
          @blur="handleTrim('exwarehouseCode')"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位查询"
          slot="searchItem4"
          @blur="handleTrim('reportInOrgName')"
        ></el-input>
        <el-input
          v-model="formData.warehouseName"
          clearable
          searchLabel="仓库"
          placeholder="请输入仓库查询"
          slot="searchItem5"
          @blur="handleTrim('warehouseName')"
        ></el-input>
        <el-date-picker
          v-model="formData.paymentApplyDate"
          searchLabel="编制日期"
          clearable
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          slot="searchItem7"
        >
        </el-date-picker>
      </el-search>
    </div>
    <!-- 表格 -->
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        :row-style="rowClass"
        :cell-style="cellStyle"
        border
        class="ccui-multifunctional-table"
        @header-dragend="tableTitleWidth"
        @sort-change="sortChange"
        max-height="9999"
      >
        <el-table-column label="序号" width="60" fixed>
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="出库单编号" width="200" fixed>
          <template slot-scope="scope">
            <span
              :style="{ color: 'rgb(0, 137, 239)', cursor: 'pointer' }"
              @click="handleGoDetail(scope.row)"
              >{{ scope.row.exwarehouseCode }}</span
            >
          </template>
        </el-table-column> -->

        <template v-for="(table, index) in unfixedTableThead">
          <el-table-column
            :fixed="table.fixed || false"
            :key="index"
            :type="table.type"
            :label="table.label"
            :align="table.align || 'left'"
            :header-align="table.headerAlign || 'left'"
            :min-width="table.width"
            :prop="table.prop"
            :show-overflow-tooltip="true"
            border="true"
          >
          </el-table-column>
        </template>
      </el-table>
      <div class="ccui-table-footer" v-show="isShowPagination">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="pageSizeCode"
            background
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleSizeChange('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
    <!-- 表格end -->
  </div>
</template>

<script>
import {
  listPageExwarehouseBillParameter,
  detailAccountExport
} from "../api/item-list";
import getPower from "@/basa/utils/getPower.js";
import { setSessionItem, getSessionItem, ishasAgentId } from "@/basa/utils";
import peopleManageMixin from "../mixins/peopleManage.js";
import approvalState from "@/config/mixins/smp-state";
// import { addUrlPerFix } from "@/basa/utils";

export default {
  mixins: [getPower, peopleManageMixin, approvalState],
  data() {
    return {
      isActive: 0,
      workStatus: "",
      isShowDetail: true,
      isShowEdit: true,
      multiDataToEnd: {},
      singleDataToEnd: {},
      // 表格相关
      tableData: [], // 表格数据
      draggFlag: true,
      tableName: this.tableList.financialMXAll, // 表格命名
      tableThead: [], // 表格数据
      // 锁定表格
      fixedTableThead: [
        {
          label: "序号",
          prop: "id",
          width: "38",
          checked: true,
          fixed: true,
          type: "index",
          resizable: false
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "出库单编号",
          prop: "exwarehouseCode",
          width: "150",
          fixed: true
        },
        {
          label: "出库单名称",
          prop: "exwarehouseName",
          width: "300"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200"
        },
        {
          label: "仓库",
          prop: "warehouseName",
          width: "180"
        },
        {
          label: "批次号",
          prop: "batchNumber",
          width: "200"
        },
        {
          label: "设备物资编码",
          prop: "materialCode",
          width: "150"
        },
        {
          label: "设备物资名称",
          prop: "materialName",
          width: "200"
        },
        {
          label: "设备物资说明",
          prop: "materialState",
          width: "130"
        },
        {
          label: "计量单位",
          prop: "measureUnit",
          width: "90"
        },
        {
          label: "出库数量",
          prop: "exwarehouseCount",
          width: "140"
        },
        {
          label: "含税单价",
          prop: "unitPriceWithTax",
          width: "140",
          align: "right"
        },
        {
          label: "含税金额",
          prop: "moneyWithTax",
          width: "140",
          align: "right"
        },
        {
          label: "币种",
          prop: "currencyName",
          width: "62"
        },
        {
          label: "汇率",
          prop: "exchangeRate",
          width: "62"
        },
        {
          label: "编制人",
          prop: "reportUsername",
          width: "80"
        },
        {
          label: "编制日期",
          prop: "reportTime",
          width: "130"
        }
      ],
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      // popoverShow: false,
      selectRow: [],
      selectData: [],
      isFocus: 1,
      // 表格相关 end
      // 高级搜索数据 start
      formData: {
        exwarehouseCode: "", // 出库单编号
        exwarehouseName: "", // 出库单名称
        reportInOrgName: "", // 填报单位名称
        warehouseName: "" // 仓库
      }, // 高级搜索提交数据
      localSearchData: {},
      isShowSearch: true,
      isShow: false,
      outboundState: [
        {
          label: "审批通过",
          value: 5
        },
        {
          label: "已冲销",
          value: 22
        }
      ],
      // 高级搜索数据 end
      isShowPagination: false, //无数据的不展示底部全选，批量删除
      // 全选以及页码
      totalNum: 0,
      total: 0,
      isIndeterminate: false,
      checkAll: false,
      value: "",
      pageNoCode: 1, // this.getLocalPageNo()
      pageSizeCode: 10, // this.getLocalPageSize()
      // isFist: false,
      // 全选以及页码 end
      // 表格数据删除相关
      delDemoId: "",
      content: "",
      typeDel: "", //有关批量删除
      isSelection: false,
      // 表格数据删除相关 end
      // 排序入参所需字段
      sortord: "",
      sortprop: "",
      // 表格数据相关处理 end
      form: {},
      formDataSearch: {},
      excelExport: [],
      excelData: [],
      deviceList: {
        exwarehouseStatus: "5,22"
      }
    };
  },
  computed: {},
  watch: {},
  methods: {
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },

    // 查看
    handleGoDetail(row) {
      // 维护的详情页
      this.$router.push({
        path: `/inventoryManagement/financeWarehousing/item-detail/${row.id}`,
        query: {
          status:
            row.storageType == "正式入库"
              ? 0
              : row.storageType == "暂估入库"
              ? 1
              : // : row.storageType == "入库冲销"
                // ? 2
                "",
          page: "standingBook"
        }
      });
    },
    initData() {
      this.isShow = false;
      this.setTableWidth();
      // this.getDatas();
      this.renderTable();
      // this.isFist = false;
    },
    // 默认渲染表格

    // 表格弹框拖拽触发
    handleTableChange(val) {
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 是否显示对应列
    handleUpdate(item, index) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (i === index) {
          this.unfixedTableThead.checked = !this.unfixedTableThead.checked;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 批量删除并刷新列表
    handleDelSelected() {
      if (this.idArrSelected) {
        this.typeDel = "all";
        this.deleteLog();
      } else {
        this.$message({
          message: "请选择您要删除的数据",
          type: "warning"
        });
      }
    },
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    // 导出当前页文件
    exportExcel() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      delete formDataSearch.isShowPageLoading;
      detailAccountExport(formDataSearch).then(res => {
        const datas = res;
        const url = window.URL.createObjectURL(
          new Blob([datas], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          })
        );
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        // a.setAttribute("download", "excel.xlsx");

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        // ________________________________________
        // if (res.data.code) {
        //   let a = document.createElement("a");
        //   a.style.display = "none";
        //   a.href = `${addUrlPerFix(
        //     process.env.VUE_APP_BASE_URL
        //   )}/apis/smp/oss/downloadByUploadId?uploadId=${
        //     res.data.data.fileRspBo.uploadId
        //   }`;
        //   a.setAttribute("download", res.data.data.fileRspBo.fileName);
        //   document.body.appendChild(a);
        //   a.click();
        // }
      });
    },
    //导出全部
    exportPdf() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      formDataSearch.pageNo = "1";
      formDataSearch.pageSize = "3000";
      delete formDataSearch.isShowPageLoading;
      detailAccountExport(formDataSearch).then(res => {
        const datas = res;
        const url = window.URL.createObjectURL(
          new Blob([datas], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          })
        );
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        // a.setAttribute("download", "excel.xlsx");

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        // ___________________________________________
        // if (res.data.code) {
        //   let a = document.createElement("a");
        //   a.style.display = "none";
        //   a.href = `${addUrlPerFix(
        //     process.env.VUE_APP_BASE_URL
        //   )}/apis/smp/oss/downloadByUploadId?uploadId=${
        //     res.data.data.fileRspBo.uploadId
        //   }`;
        //   a.setAttribute("download", res.data.data.fileRspBo.fileName);
        //   document.body.appendChild(a);
        //   a.click();
        // }
      });
    },
    // 高级搜索 end
    // 金额四舍五入
    calculateFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 3);
          return newData;
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    // 数量四舍五入
    numberFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 4);
          return Number(newData).toFixed();
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    // 列表数据请求
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.reportTimeStart = obj.paymentApplyDate
        ? new Date(obj.paymentApplyDate[0]).getTime()
        : "";
      obj.reportTimeEnd = obj.paymentApplyDate
        ? new Date(obj.paymentApplyDate[1]).getTime()
        : "";
      obj.pageSize = this.pageSizeCode;
      obj.isShowPageLoading = true;
      // obj.reportInOrgId = JSON.parse(window.sessionStorage.userDetal).orgId;
      listPageExwarehouseBillParameter(obj)
        .then(res => {
          console.log(res);
          if (res.data.data.rows.length == 0 && this.pageNoCode > 1) {
            this.pageNoCode--; //自减一页
            //重新自调用接口
            this.getList();
            return;
          }
          this.isShowPagination = res.data.data.recordsTotal > 0;
          this.tableData = res.data.data.rows;
          this.excelData = this.tableData;
          this.totalNum = res.data.data.recordsTotal;
          this.total = res.data.data.total;
          this.pageNoCode = res.data.data.pageNo; // 当前页
          this.tableData.forEach(item => {
            item.exwarehouseCount = (+item.exwarehouseCount).toFixed(3);
            item.unitPriceWithTax = (+item.unitPriceWithTax).toFixed(2);
            item.moneyWithTax = (+item.moneyWithTax).toFixed(2);
            if (item.reportTime) {
              item.reportTime = item.reportTime.substring(
                0,
                item.reportTime.indexOf(" ")
              );
            }
          });
        })
        .catch(e => {});
    },

    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      const arr = [];
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
          arr.push(row.id);
        });
        this.idArrSelected = arr;
      }
    },
    // 排序
    sortChange(params) {
      this.sortord = params.order;
      this.sortprop = params.prop;
      this.getList();
    },
    // 默认显示多少条
    getLocalPageSize() {
      return getSessionItem("pageSize", this.tableList.financialMXAll) || 10;
    },
    // 读取当前页缓存
    getLocalPageNo() {
      let localData = getSessionItem("pageNo", this.tableList.financialMXAll);
      return (localData && localData.pageNo) || 1;
    },
    // input 输入框去掉前后空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    }
  },
  created() {},
  mounted() {
    this.initData();
  },
  beforeRouteLeave(to, from, next) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  },
  activated() {
    this.$refs.search.resetForm();
    this.search(this.formData);
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    let localData = getSessionItem("pageNo", this.tableList.financialMXAll);
    let data = localData && localData.searchForm;
    this.getList({ ...this.formDataSearch, ...data });
  }
};
</script>
<style lang="scss" scoped>
/deep/.ccui-multifunctional-table {
  .el-table__fixed-right,
  .el-table__fixed {
    height: 100% !important;
  }
}
/deep/.el-search .el-searchs-bottom .el-form .el-row .el-col-12 {
  width: 33.33333%;
}
// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}
/deep/ .el-table__fixed,
/deep/.el-table__fixed-right {
  pointer-events: none;
  td {
    pointer-events: auto;
  }
}

/deep/ .el-searchs-box {
  width: 405px !important;
}

/deep/
  .ccui-multifunctional-table-wrapper
  .el-table
  tbody
  tr
  td:last-child
  .cell {
  padding-left: 10px !important;
  padding-right: 5px !important;
}
</style>
